<?php

namespace App\HttpController\Admin;

use App\HttpController\BaseController;
use App\Utility\Token;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\Http\Message\Status;

class Auth extends BaseController {

    protected $token;

    public function onRequest(?string $action): ?bool{
        $header = $this->request()->getHeaders();
        if(!isset($header['authorization'])){
            $this->response()->withStatus(Status::CODE_UNAUTHORIZED);
            $this->response()->write('Sorry,Unauthenticated.');
            return false;
        }
        list ($bearer, $token) = explode(' ',$header['authorization'][0]);
        if(!$token){
            $this->response()->withStatus(Status::CODE_UNAUTHORIZED);
            $this->response()->write('Sorry,Unauthenticated.');
            return false;
        }
        if(!Token::sessionCheckToken($token)){
            $this->response()->withStatus(Status::CODE_UNAUTHORIZED);
            $this->response()->write('Sorry,Unauthenticated.');
            return false;
        }
        $this->token = $token;
        return true;
    }

    public function __destruct(){
        unset($this->token);
    }



}
